package com.example.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;

import java.io.IOException;

/**
 * @author 23050
 * @version 1.0
 * @description: TODO
 * @date 2025/2/28 23:23
 */
public class AliUtil {
    
    

    public static void main(String[] args) throws IOException {
        String prompt = "print(\"Hello\")\n" +
                "print(\"World\")\n";
        getComplation(prompt);
    }

    public static String getComplation(String prompt) {

        try {

            long start = System.currentTimeMillis();
            //格式化选中的代码块
            String json =  modelStr(prompt);


            //请求大模型
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
            Request request = new Request.Builder()
                    .url("https://dashscope.aliyuncs.com/compatible-mode/v1/completions")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("Authorization", "Bearer sk-5bffade0f3fb46d49abf169956ca460e")
                    .build();

            Call call = new OkHttpClient().newCall(request);
            Response response = null;
            try {
                response = call.execute();
            } catch (IOException e) {
                System.out.println("execute failed, message:" + e.getMessage());
            }



            //获取想要的数据
            String jsonStr = response.body().string();
            System.out.println(jsonStr);
            // 解析 JSON 字符串
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            // 获取 choices 数组
            JSONArray choicesArray = jsonObject.getJSONArray("choices");
            if (choicesArray != null && !choicesArray.isEmpty()) {
                // 获取数组的第一个元素
                JSONObject firstChoice = choicesArray.getJSONObject(0);
                // 提取 text 属性
                String text = firstChoice.getString("text");
                System.out.println(text);
                long end = System.currentTimeMillis();
                System.out.println(end-start);
                return text;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "空";
    }



    private static String modelStr(String prompt) {
        System.out.println("选中的数据"+prompt);
        String s = prompt.replaceAll("\n", "\\\\n");
        String s1 = s.replaceAll("\"", "\\\\\"");
        prompt =  s1;
        System.out.println("prompt:"+prompt);


        String json ="{\n" +
                "  \"model\": \"qwen-coder-turbo\",\n" +
                "  \"prompt\":\" " + prompt +"  \" ,\n " +
                "  \"max_tokens\": 64\n" +
                "}";
        System.out.println("json:"+json);
        return json;
    }

}
